package com.example.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.entity.Account;
import com.example.service.AdminService;
import com.example.service.UserService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

@Component
public class TokenUtils {
    @Resource
    AdminService adminService;
    @Resource
    UserService userService;

    static UserService staticUserService;
    static AdminService staticAdminService;
    // SpringBoot启动时，会调用该方法
    @PostConstruct
    public void init() {
        staticUserService = userService;
        staticAdminService = adminService;
    }
    //  生成token
    public static String createToken(String data,String sign) {
        return JWT.create()
                .withAudience(data) //  将userId-role保存到token里面，作为载荷
                .withExpiresAt( DateUtil.offsetDay(new Date(), 1)) //  设置token过期时间--一天后
                .sign(Algorithm.HMAC256(sign)); //  使用HS256加密算法，以password作为密钥，生成token
    }

    //
    public static Account getCurrentUser() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)){
           token = request.getParameter("token");
        }

        // 获取token中的载荷数据
        String audience = JWT.decode(token).getAudience().get(0);
        String[] split = audience.split("-");
        Integer userId = Integer.parseInt(split[0]);
        String role = split[1];
        // 根据tooken中获取的id和role，查询用户
        if  ("ADMIN".equals(role)){
            return staticAdminService.selectById(userId);
        }else if("USER".equals(role)){
            return staticUserService.selectById(userId);
        }
        return null;
    }
}
